#include "StdAfx.h"
#include "Decompressor.h"

using namespace std;
Decompressor::Decompressor(vector<unsigned char> data, unsigned int paddingLength)throw(IllegalArgumentException)
{
	if (data.empty()){
		throw IllegalArgumentException("Decompressor Rle8: image data is empty");
	}
	_data = data;
	_paddingLength = paddingLength;
}


Decompressor::~Decompressor(void)
{
}

vector<unsigned char> Decompressor::Rle8(){

	vector<unsigned char> tmpData, data;
	unsigned char code, coutner;
	bool absoluteMode = false;

	for (int i=0; i<_data.size();i++){
		code=_data[i];

		if (code==0){
			absoluteMode = true;
		}else{
			absoluteMode = false; //encoded mode
		}
		tmpData=readDataRle8(absoluteMode, &i);
		data.insert(data.end(),tmpData.begin(),tmpData.end());
	}
	

	return data;
}

vector<unsigned char> Decompressor::readDataRle8(bool absoluteMode, int *dataIndex)
{
	vector<unsigned char> tmp;

	if (absoluteMode==true){
		(*dataIndex)++;
		unsigned char counter = _data[*dataIndex];
		if(counter>2){	//uncompressed data
			(*dataIndex)++;
			tmp.resize(counter);
			for (unsigned char i=0; i<counter; i++ ){
				tmp[i] = _data[*dataIndex];
				(*dataIndex)++;
			}
			if (counter%2==0){
				(*dataIndex)--;
			}
		}else if (counter==0){ //end of line
			tmp.clear();
			tmp.resize(_paddingLength);
		}else if (counter==1){ //end of bitmap
			tmp.clear();
			tmp.resize(_paddingLength);
			(*dataIndex)++;
		}else if (counter==2){ //delta
			// delta implementation :)
			// no need for gray scale image 
		}
	}

	if(absoluteMode==false){  //encoding mode
		unsigned char counter = _data[*dataIndex];
		tmp.resize(counter);
		(*dataIndex)++;
		for (unsigned char i=0; i<counter;i++){
			tmp[i]=_data[*dataIndex];
		}
	}
	return tmp;
}

